<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>利用闭包根据字段排序商品</title>
</head>

<body>

</body>
<script>
  "use strict"; {
    let data = [{
      title: "go",
      click: 780,
      price: 100
    }, {
      title: "java",
      click: 80,
      price: 22
    }, {
      title: "js",
      click: 10,
      price: 10
    }, {
      title: "php",
      click: 100,
      price: 133
    }];

    // 按照价格进行升序排序
    let hd = data.sort((a, b) => {
      return a.price - b.price;
    });
    // console.log(JSON.stringify(hd, null, 2));
    // 按照价格进行降序排序
    let ja = data.sort((a, b) => {
      return b.price - a.price;
    });
    // console.log(JSON.stringify(ja, null, 2));

    // 使用闭包将两个合并起来
    let order = (field, type = "asc") => {
      return (a, b) => {
        if (type === "asc") return a[field] - b[field];
        return b[field] - a[field];
      };
    };
    console.log(JSON.stringify(data.sort(order("price","desc")), null, 2));
    console.log(JSON.stringify(data.sort(order()), null, 2));
  };
</script>

</html>